/**
 * 
 */
package org.threebitsoftware.tbb.module.simpletext;

import javax.swing.JPanel;

import java.io.*;
import java.util.Vector;

import org.threebitsoftware.tbb.dao.Address;
import org.threebitsoftware.tbb.dao.EmailAddress;
import org.threebitsoftware.tbb.dao.PhoneNumber;
import org.threebitsoftware.tbb.dao.Contact;
import org.threebitsoftware.tbb.module.fileio.FileImportInterface;

/**
 * @author ABBA
 *
 */
public class SimpleTextImporter implements FileImportInterface {

	@Override
	public Contact[] parseFile(String myStrFilePath) throws Exception {
		Contact[] myContacts = null;
		BufferedReader in = null;
		
		try {
			String line = null;
			int numberOfContacts = 0;
			
			in = new BufferedReader(new FileReader(myStrFilePath));
			
			// Grab the number of contacts
			if ((line = in.readLine()) != null) {
				
				String[] parsedStr = line.split(":");
					
				if ((parsedStr.length == 2) &&
					(parsedStr[0].equals("Number of Contacts"))) {
					
					numberOfContacts = Integer.parseInt(parsedStr[1]);
					
					if (numberOfContacts < 1) {
						in.close();
						return myContacts;
					}
				} else {
					in.close();
					return myContacts;
				}
			} else {
				in.close();
				return myContacts;
			}
			
			Vector <Contact> vectorContacts = new Vector<Contact>();
			
			for (int contactIndex = 1;
			     contactIndex <= numberOfContacts;
			     contactIndex++) {
				
				if (((line = in.readLine()) != null) &&
					(line.length() > 0) &&
					(line.equals("Contact Begin"))) {
					
					Vector <Address> vectorAddress = new Vector<Address>();
					Vector <PhoneNumber> vectorPhoneNumber = new Vector<PhoneNumber>();
					Vector <EmailAddress> vectorEmail = new Vector<EmailAddress>();
					Contact myContact = null;
					
					// Collect the contact information
					
				    while (((line = in.readLine()) != null) &&
				    		(line.length() > 0) &&
				    		(!(line.equals("Contact End")))) {
				    	
				    	/* Format: "[type string]:   [data string]"
				    	 * 
				    	 * "type string" definitions
				    	 * 
				    	 *		Contact Name			
				    	 *		Identification
				    	 *		Address
				    	 *		Phone Number
				    	 *		E-Mail Address
				    	 * 
				    	 */
				    	String[] parsedStr = line.split(":");
				    		
				    	if (parsedStr.length == 2) {
				    		
				    		String typeStr = parsedStr[0];
				    		String trimmedDataStr = parsedStr[1].trim();
				    		String[] parsedDataStr2 = trimmedDataStr.split("=|[\\s]{3}");
				    		int parsedDataStrLen = parsedDataStr2.length;
				    			
				    		if (typeStr.equals("Contact Name")) {
				    				
				    			/* Format: Prefix=<value>   First=<value>   
				    			 *         Last=<value>   Middle=<value>
				    			 *         Suffix=<value>   Title=<value>
				    			 *         Company=<value>   Is Person=<value>
				    			 */
				    			String prefixStr = "";
				    			String firstStr = "";
				    			String lastStr = "";
				    			String middleStr = "";
				    			String suffixStr = "";
				    			String titleStr = "";
				    			String companyStr = "";
				    			boolean isPerson= false;
				    				
				    			for (int i = 0; i < parsedDataStrLen; i += 2) {
				    					
				    				String dataType = parsedDataStr2[i];
				    				String dataStr = parsedDataStr2[(i + 1)];
				    					
				    				if (dataType.equals("Prefix")) {
				    					prefixStr = dataStr;
				    				}
				    				else if (dataType.equals("First")) {
				    					firstStr = dataStr;
				    				}
				    				else if (dataType.equals("Last")) {
				    					lastStr = dataStr;
				    				}
				    				else if (dataType.equals("Middle")) {
				    					middleStr = dataStr;
				    				}
				    				else if (dataType.equals("Suffix")) {
				    					suffixStr = dataStr;
				    				}
				    				else if (dataType.equals("Title")) {
				    					titleStr = dataStr;
				    				}
				    				else if (dataType.equals("Company")) {
				    					companyStr = dataStr;
				    				}
				    				else if (dataType.equals("Is Person")) {
				    					isPerson = dataStr.equals("true");
				    				}
				    			}
				    				
				    			if ((!prefixStr.isEmpty()) ||
				    				(!firstStr.isEmpty()) ||
				    				(!lastStr.isEmpty()) ||
				    				(!middleStr.isEmpty()) ||
				    				(!suffixStr.isEmpty()) ||
				    				(!titleStr.isEmpty()) ||
				    				(!companyStr.isEmpty())) {
				    				myContact = 
				    					new Contact(firstStr, lastStr, middleStr,
				    							suffixStr, prefixStr, companyStr,
				    							titleStr, isPerson);
				    			}
				    		}
			    			else if (typeStr.equals("Identification")) {
			    				
				    			/* Format: [UI]:<value>   [CI]:<value>
				    			 * 
				    			 * Definitions:
				    			 * 
				    			 * UI = User Application ID
				    			 * CI = Contact ID
					    		 * 
					    		 */
				    			int idAppUser = -1;
				    			int idContact = -1;
				    				
				    			for (int i = 0; i < parsedDataStrLen; i += 2) {
				    					
				    				String dataType = parsedDataStr2[i];
				    				int dataInt = Integer.parseInt(parsedDataStr2[(i + 1)]);
				    					
				    				if (dataType.equals("AUID")) {					
				    					idAppUser = dataInt;
				    				}
			    					else if (dataType.equals("CID")) {
			    						idContact = dataInt;
			    					}
			    				}
				    				
			    				if ((idAppUser != -1) &&
			    					(idContact != -1) &&
			    					(myContact != null)) {
				    					myContact.setIdAppUser(idAppUser);
				    					myContact.setIdContact(idContact);
			    				}
			    			}

			    			else if (typeStr.equals("Address")) {
			    				
			    				/* Format: Description=<value>   Street1=<value>
			    				 *         Street2=<value>   Street3=<value>
			    				 *         City=<value>   Province=<value>
			    				 *         Country=<value>   Zip Code=<value>
			    				 */
			    				String descStr = "";
			    				String street1Str = "";
			    				String street2Str = "";
			    				String street3Str = "";
			    				String cityStr = "";
			    				String provinceStr = "";
			    				String countryStr = "";
			    				String zipCodeStr = "";
			    				int idContact = -1;
			    				int idAddress = -1;
			    				
			    				for (int i = 0; i < parsedDataStrLen; i += 2) {
			    					
			    					String dataType = parsedDataStr2[i];
			    					String dataStr = parsedDataStr2[(i + 1)];
			    					
			    					if (dataType.equals("Description")) {
			    						
			    						descStr = dataStr;
			    					}
			    					else if (dataType.equals("Street1")) {
			    						street1Str = dataStr;
			    					}
			    					else if (dataType.equals("Street2")) {
			    						street2Str = dataStr;
			    					}
			    					else if (dataType.equals("Street3")) {
			    						street3Str = dataStr;
			    					}
			    					else if (dataType.equals("City")) {
			    						cityStr = dataStr;
			    					}
			    					else if (dataType.equals("Province")) {
			    						provinceStr = dataStr;
			    					}
			    					else if (dataType.equals("Country")) {
			    						countryStr = dataStr;
			    					}
			    					else if (dataType.equals("Zip Code")) {
			    						zipCodeStr = dataStr;
			    					}
			    					else if (dataType.equals("CID")) {
			    						idContact = Integer.parseInt(dataStr);
			    					}
			    					else if (dataType.equals("AID")) {
			    						idAddress = Integer.parseInt(dataStr);
			    					}
			    				}
			    				
			    				if ((!street1Str.isEmpty()) ||
			    					(!street2Str.isEmpty()) ||
			    					(!street3Str.isEmpty()) ||
			    					(!cityStr.isEmpty()) ||
			    					(!provinceStr.isEmpty()) ||
			    					(!countryStr.isEmpty()) ||
			    					(!zipCodeStr.isEmpty())) {
			    					
			    					Address address =
			    						new Address (street1Str, street2Str,
			    								street3Str, countryStr, zipCodeStr,
			    								provinceStr, cityStr, descStr,
			    								idContact, idAddress);
			    					
			    					vectorAddress.add(address);
			    				}
			    			}
			    			else if (typeStr.equals("Phone Number")) {
			    				
			    				/* Format: Description=<value>   Number=<value>
			    				 * 
			    				 */
			    				String descStr = "";
			    				String phoneNumberStr = "";
			    				int idPhoneNumber = -1;
			    				int idContact = -1;
			    				
			    				for (int i = 0; i < parsedDataStrLen; i += 2) {
			    					
			    					String dataType = parsedDataStr2[i];
			    					String dataStr = parsedDataStr2[(i + 1)];
			    					
			    					if (dataType.equals("Description")) {
			    						descStr = dataStr;
			    					}
			    					else if (dataType.equals("Number")) {
			    						phoneNumberStr = dataStr;
			    					}
			    					else if (dataType.equals("PID")) {
			    						idPhoneNumber = Integer.parseInt(dataStr);
			    					}
			    					else if (dataType.equals("CID")) {
			    						idContact = Integer.parseInt(dataStr);
			    					}
			    				}
			    				
			    				if (!phoneNumberStr.isEmpty()) {
			    					
			    					PhoneNumber phoneNumber =
			    						new PhoneNumber (phoneNumberStr,
			    								descStr, idPhoneNumber,
			    								idContact);
			    					
			    					vectorPhoneNumber.add(phoneNumber);
			    				}
			    			}
			    			else if (typeStr.equals("E-mail Address")) {
			    				
			    				/* Format: Description=<value>   E-Mail=<value>
			    				 * 
			    				 */
			    				String descStr = "";
			    				String emailStr = "";
			    				int idAppUser = -1;
			    				int idContact = -1;
			    				
			    				for (int i = 0; i < parsedDataStrLen; i += 2) {
			    					
			    					String dataType = parsedDataStr2[i];
			    					String dataStr = parsedDataStr2[(i + 1)];
			    					
			    					if (dataType.equals("Description")) {
			    						
			    						descStr = dataStr;
			    					}
			    					else if (dataType.equals("E-mail")) {
			    						emailStr = dataStr;
			    					}
			    					else if (dataType.equals("AUID")) {
			    						idAppUser = Integer.parseInt(dataStr);
			    					}
			    					else if (dataType.equals("CID")) {
			    						idContact = Integer.parseInt(dataStr);
			    					}
			    				}
			    				
			    				if (!emailStr.isEmpty()) {
			    					
			    					EmailAddress email =
			    						new EmailAddress(emailStr, descStr,
			    								idAppUser, idContact);
			    					
			    					vectorEmail.add(email);
			    				}
			    			}
				    		
			    		} // End of if (parsedStr.length == 2) statement
				    } // End of while (((line = in.readLine()) != null...) loop
				    
				    /* Once the contact information has been collected add
				     * put it together and add it to the list of contacts
				     */
				    if (myContact != null) {
				    	
				    	if (!vectorAddress.isEmpty()) {
				    		myContact.setAddresses(vectorAddress);
					    }
				    	
				    	if (!vectorPhoneNumber.isEmpty()) {
				    		myContact.setPhoneNumbers(vectorPhoneNumber);
				    	}
				    	
				    	if (!vectorEmail.isEmpty()) {
				    		myContact.setEmails(vectorEmail);
				    	}
				    	
				    	vectorContacts.add(myContact);
				    }
				} // End of if (((line = in.readLine()) != null) ... statement
			} // End of for (...) loop
			
			myContacts = VectorToArray(vectorContacts);
		    
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				in.close();
			}
		}
		
		return myContacts;
	}

	@Override
	public JPanel getGUI() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getMergeClassName() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean iHaveMyOwnGUI() {
		// TODO Auto-generated method stub
		return false;
	}
	
	private Contact[] VectorToArray(Vector<Contact> vectorContacts) {
		
		int numberOfContacts = vectorContacts.size();
		Contact[] myContacts = null;
		
		if (numberOfContacts > 0) {
			
			myContacts = new Contact[numberOfContacts];
			
			int contactIndex = 0;
			for (Contact myContact : vectorContacts) {
				myContacts[contactIndex++] = myContact;
			}
		}
		
		return myContacts;
	}

}
